package csu.web.mypetstore.web.servlet;
import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.service.CartService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "AddItemToServlet", urlPatterns = {"/addItemToCart"})

public class AddItemToServlet extends HttpServlet {
    private CartService cartService;
    public AddItemToServlet()
    {
        cartService=new CartService();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session=req.getSession();
        Account loginAccount=(Account) session.getAttribute("loginAccount");
        String workingItemId=req.getParameter("workingItemId");
        if(loginAccount==null)
        {
            resp.sendRedirect("signonForm");//登陆后才能添加购物车
            return;
        }
        else {
            cartService.addItemToCart(loginAccount.getUsername(),workingItemId);
        }

        session.setAttribute("action","addedItemToCart");

        //重定向到购物车页面，避免刷新加1问题
        resp.sendRedirect("cartForm");


    }
}
